<template>
  <!--工厂建模-->
  <div class="alarmConfiguration content">
    <div class="left-side" style="width: 100%;margin-bottom: 20px">
      <!-- 左侧内容 -->
      <div class="left-content">
        <div class="button_but_top">
<!--          <h2 style="margin-right: 10px">生产关系设置</h2>-->
          <el-button type="primary" icon="Plus" :disabled="lineData.length > 0" @click="showModal('add', { level: 0 })">
            新建节点
          </el-button>
          <!-- 添加列按钮 -->
          <!--					<el-button  @click="showAddColumnDialog = true" type="primary">表头列配置</el-button>-->
        </div>
        <el-table ref="selection" @selection-change="handleSelectionChange" height="calc(100vh - 680px)" row-key="id"
                  :data="lineData" border @column-width-resize="onDragEnd">
          <el-table-column prop="name" label="名称" tree draggable></el-table-column>
          <el-table-column prop="code" label="编码" align="center" draggable></el-table-column>
          <!-- 动态列渲染 -->
          <!--          <el-table-column v-for="col in columns" :key="col.tableKey" :prop="col.tableKey" :label="col.tableChineseKey"-->
          <!--                           align="center"/>-->
          <el-table-column label="操作" align="center" fixed="right" draggable>
            <template #default="{ row }">
              <div class="button_but">
                <el-button type="text" size="small" @click="showModal('edit', row)">修改</el-button>
                <el-button type="text" size="small" @click="showModal('next', row)" v-if="row.layer < 3">添加下级
                </el-button>
                <el-button type="text" size="small" @click="delShow(row, 'isAll')">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="right-side" style="width: 100%;">
      <!-- 右侧内容 -->
      <div class="right-content">
        <h2>产线结构</h2>
        <div ref="chartDom" style="width: 99%; height:350px;"></div>
      </div>
    </div>
    <el-dialog v-model="visible" :title="titleName(title)" :close-on-click-modal="false" width="500">
      <el-form :model="form" label-position="top"  label-width="130px" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码"/>
        </el-form-item>
        <!-- 动态字段在弹窗中渲染 -->
        <!--        <el-form-item v-for="col in columns" :key="col.tableKey" :label="col.tableChineseKey" :prop="col.tableKey">-->
        <!--          <el-input v-model="form[col.tableKey]" :placeholder="`请输入${col.tableChineseKey}`" style="width: 100%"/>-->
        <!--        </el-form-item>-->
        <!-- <el-form-item label="产品名称" prop="product_id">
          <el-select v-model="form.product_id" placeholder="请选择产品名称">
            <el-option v-for="(item, index) in materialList" :key="index" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="closeModal">取消</el-button>
					<el-button type="primary" @click="handleSubmit('form')">确定</el-button>
				</span>
      </template>
    </el-dialog>
    <el-dialog :mask-closable="false" v-model="deleteShow" title="删除" class="modal-title-layout">
      <p class="title">
        <span>是否确认删除?</span>
      </p>
      <template #footer>
        <el-button type="default" @click="deleteShow = false">取消</el-button>
        <el-button type="primary" @click="handleDeleteSure">确定</el-button>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog" title="管理列信息">
      <!-- 表格增删改查 -->
      <el-button icon="Plus" @click="showAddColumnDialog2 = true; columnDialogTitle = '新建'" type="primary"
                 style="margin-bottom: 20px;">新建列
      </el-button>
      <el-table :data="columns">
        <el-table-column prop="tableChineseKey" label="列名称" align="center"/>
        <el-table-column prop="tableKey" label="列编码" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button @click="editColumn(scope.row, scope.$index)" size="small" icon="Edit">编辑</el-button>
            <el-button @click="deleteColumn(scope.row, scope.$index)" size="small" type="danger" icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>


      <template #footer>
        <el-button @click="showAddColumnDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog2" :title="columnDialogTitle">
      <el-form>
        <el-form-item label="列名称">
          <el-input v-model="newColumn.tableChineseKey" placeholder="请输入列名称"/>
        </el-form-item>
        <el-form-item label="列Key">
          <el-input v-model="newColumn.tableKey" placeholder="请输入列Key"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddColumnDialog2 = false">取消</el-button>
        <el-button type="primary" @click="addColumn">确定</el-button>
      </template>
    </el-dialog>

  </div>

</template>
<script setup lang="ts">
import {addLine, deltLine, editLine, lineAll} from '@/api/baseData/productionLine';
import axiosInstance from '@/utils/http/api';
import * as echarts from 'echarts';
import {ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElMessage, ElTable, ElTableColumn} from 'element-plus';
import {onMounted, ref, watch} from 'vue';

// 状态变量
const visible = ref(false);
const title = ref('');
const form = ref({});
const lineData = ref([]);
const deleteShow = ref(false);
const paramsItem = ref({});
const ids = ref([]);
const chartDom = ref(null);
const containerHeight = ref(0);

// 表单验证规则
const rules = {
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入编码', trigger: 'blur'}
  ]
};

// 标题映射函数
const titleName = (type) => {
  const titles = {
    add: '新建节点',
    edit: '修改节点',
    next: '新建子节点'
  };

  return titles[type] || '未知操作';
};


// 获取列表数据
const listFetch = () => {
  axiosInstance.post('/api/basedata/factoryModel/getAll',)
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        if (res.code === 200) {
          lineData.value = buildTree(res.data.map((item) => {
            return {
              ...item.extension,
              ...item
            };
          }));
          const drawData = buildTree(res.data.map((item) => {
            return {
              ...item.extension,
              ...item
            };
          }));
          drawChart(drawData, chartDom.value);

          console.log(lineData.value, ' lineData.value')
        }
        // equipmentData.value = res.data.records;
      });
  // lineAll({current: 1, pageSize: 100000}).then((res) => {
  //   if (res.code === 200) {
  //     lineData.value = buildTree(res.data.records.map((item) => {
  //       return {
  //         ...item.extension,
  //         ...item
  //       };
  //     }));
  //     const drawData = buildTree(res.data.records.map((item) => {
  //       return {
  //         ...item.extension,
  //         ...item
  //       };
  //     }));
  //     drawChart(drawData, chartDom.value);
  //   }
  // });
};

// 构建树形结构
const buildTree = (items) => {
  const itemMap = {};
  const rootItems = [];
  items.forEach((item) => {
    itemMap[item.id] = {...item, name: item.name, children: []};
  });
  items.forEach((item) => {
    if (!item.parentId || item.parentId === '0') {
      rootItems.push(itemMap[item.id]);
    } else {
      if (itemMap[item.parentId]) {
        itemMap[item.parentId].children.push(itemMap[item.id]);
      }
    }
  });

  return rootItems;
};

// 绘制图表
const drawChart = (data, dom) => {
  const myChart = echarts.init(dom);
  myChart.setOption({
    tooltip: {
      trigger: 'item',
      triggerOn: 'mousemove'
    },
    series: [
      {
        type: 'tree',
        data,
        top: '1%',
        left: '7%',
        bottom: '1%',
        right: '20%',
        symbolSize: 7,
        label: {
          position: 'left',
          verticalAlign: 'middle',
          align: 'right',
          fontSize: 9
        },
        leaves: {
          label: {
            position: 'right',
            verticalAlign: 'middle',
            align: 'left'
          }
        },
        emphasis: {
          focus: 'descendant'
        },
        expandAndCollapse: true,
        animationDuration: 550,
        animationDurationUpdate: 750
      }
    ]
  });
};

// 显示模态框
const showModal = (type, row) => {
  if (type !== 'edit') {
    form.value = {};
  } else {
    form.value = {...row};
  }
  if (type === 'next') {
    form.value.layer = Number(row.layer) + 1; // 确保父节点有 layer 字段
  }
  console.log(type, row, 'type,row');
  title.value = type;
  visible.value = true;
  paramsItem.value = row;
};

// 关闭模态框
const closeModal = () => {
  visible.value = false;
};

// 提交表单
// 提交表单
// 提交表单
const handleSubmit = (formName) => {
  // 获取表单实例
  let apiCall;
  let payload;
  const formObject = columns.value.reduce((acc, col) => {
    acc[col.tableKey] = form.value[col.tableKey];
    return acc;
  }, {});
  console.log(formObject);
  form.value.extension = formObject;
  console.log(form.value, 'form.value', title.value);
  if (title.value === 'add') {
    apiCall = addLine;
    payload = form.value;
  } else if (title.value === 'edit') {
    apiCall = editLine;
    payload = {...form.value, id: paramsItem.value.id};
  } else if (title.value === 'next') {
    apiCall = addLine;
    payload = {...form.value, parentId: paramsItem.value.id};
  }

  apiCall(payload).then((res) => {
    if (res.code === 200) {
      visible.value = false;
      listFetch();
    } else {
      ElMessage.warning(res.message);
    }
  });
};
// 选择项变化
const handleSelectionChange = (selectionData) => {
  console.log(selectionData);
  ids.value = selectionData.map((item) => item.id);
};

// 删除确认
const handleDeleteSure = () => {
  deltLine({ids: ids.value}).then((res) => {
    if (res.code === 200) {
      deleteShow.value = false;
      listFetch();
    } else {
      ElMessage.warning(res.message);
    }
  });
};

// 显示删除对话框
const delShow = (row, delType) => {
  if (delType === 'isAll') {
    ids.value = [row.id];
  }
  deleteShow.value = true;
};

// 拖拽结束
const onDragEnd = (newColumns) => {
  // Handle drag end logic here
};

// 更新容器高度
const updateContainerHeight = () => {
  containerHeight.value = window.innerHeight - 150; // 减去顶部和底部的 padding
};

// 生命周期钩子
onMounted(() => {
  listFetch();
  getColumnsList();
  updateContainerHeight();
  window.addEventListener('resize', updateContainerHeight);
});

watch(() => visible.value, (newVal) => {
  if (!newVal) {
    form.value = {};
  }
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateContainerHeight);
});
// 动态列和新列的数据
const columns = ref([
  {tableChineseKey: '自定义列1', tableKey: 'tableKey', visible: true},
  {tableChineseKey: '自定义列2', tableKey: 'tableKey', visible: true}
  // 可添加更多默认列
]);
const showAddColumnDialog = ref(false);
const showAddColumnDialog2 = ref(false);
const columnDialogTitle = ref('');
const columnIndexNumber = ref(0);

const newColumn = ref({
  tableChineseKey: '',
  tableKey: '',
  visible: true,
  id: ''
});
// 查询列
const getColumnsList = () => {
  // axiosInstance.post('/api/dynamicTableExtension/getPage',
  //     {page: 1, pageSize: 999, tableName: 'productionLine'}
  // ).then(res => {
  //   const {data, code, message} = res;
  //   if (code === 200) {
  //     columns.value = data.records;
  //   }
  // });
};
// 新建列
const addColumn = () => {
  console.log('编辑');

  if (newColumn.value.tableKey && newColumn.value.tableChineseKey) {

    if (columnDialogTitle.value === '新建') {
      axiosInstance.post('/api/dynamicTableExtension/save', {
        'frontendType': 'INPUT',
        'tableName': 'productionLine',
        'tableKey': newColumn.value.tableKey,
        'tableChineseKey': newColumn.value.tableChineseKey
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('新建列成功');
          getColumnsList();
          // columns.value.push({ ...newColumn.value });
          newColumn.value = {tableKey: '', tableChineseKey: '', visible: true};
          showAddColumnDialog2.value = false;
        }
      });

    } else {
      console.log('编辑');
      axiosInstance.put('/api/dynamicTableExtension/update', {
        'frontendType': 'INPUT',
        'tableName': 'productionLine',
        'tableKey': newColumn.value.tableKey,
        'tableChineseKey': newColumn.value.tableChineseKey,
        'id': newColumn.value.id

      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('修改成功');
          getColumnsList();
          showAddColumnDialog2.value = false;

        }
      });

    }

  }
};

// 编辑列
const editColumn = (row: any, index: number) => {
  console.log(row);
  columnIndexNumber.value = index;
  columnDialogTitle.value = '编辑';
  showAddColumnDialog2.value = true;
  newColumn.value.tableChineseKey = row.tableChineseKey;
  newColumn.value.tableKey = row.tableKey;
  newColumn.value.id = row.id;


};

// 删除列
const deleteColumn = (row: any, index: number) => {
  axiosInstance.delete('/api/dynamicTableExtension/delete', {
    data: {
      ids: [row.id]
    }
  }).then(res => {
    if (res.code === 200) {
      getColumnsList();
      ElMessage.success('修改成功');

    }
  });
  // columns.value.splice(index, 1);
};
</script>
<style scoped lang="less">
.alarmConfiguration {
  display: block;
  box-sizing: border-box;

  border: 1px solid #e5e5e5;

  .button_but_top {
    margin-bottom: 10px;
    display: flex;

    button {
      margin: 0 5px;
    }
  }

  .button_but {
    display: flex;
    justify-content: center;

    button {
      margin: 0 1px;
    }
  }

  .left-side,
  .right-side {
    box-sizing: border-box;
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #e5e5e5;
    //margin-bottom: 20px;
    /* 添加间距 */
  }

  .left-side {
    max-width: 100%;
    overflow-y: auto;
  }

  .right-side {
    width: 100%;
    overflow-y: auto;
  }

  .left-content,
  .right-content {
    h2 {
      margin-bottom: 10px;
    }
  }
}
</style>
